package com.tarena.practice.sso.service;

import java.util.Date;
import java.util.List;

import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.tarena.practice.sso.mapper.UserMapper;
import com.tarena.practice.sso.pojo.User;
import com.tarena.practice.sso.redis.RedisService;
import com.tarena.practice.sso.util.MailUtils;
import com.tarena.practice.sso.vo.SysResult;


@Service
public class UserService {
	@Autowired
	private UserMapper userMapper;

	public Boolean check(String param, Integer type) {

		User user = new User();

		switch (type) {
		case 1:
			user.setUsername(param);
			break;

		case 2:
			user.setPhone(param);
			break;

		default:
			user.setEmail(param);
			break;
		}

		List<User> users = userMapper.select(user);

		if (users != null && users.size() > 0)
			return true;

		return false;
	}

	public void register(User user) {
		user.setCreated(new Date());
		user.setUpdated(user.getCreated());
		String md5pw = DigestUtils.md5Hex(user.getPassword());
		user.setPassword(md5pw);
		userMapper.insert(user);
		MailUtils.activateMail(user);// 发送邮件到用户邮箱,次行代码需要放入SSO处
	}

	@Autowired
	private RedisService redisService;
	public static final ObjectMapper mapper = new ObjectMapper();

	public SysResult login(String u, String p) throws Exception {
		String ticket = "";
		User _user = new User();
		_user.setUsername(u);
		User user = userMapper.selectOne(_user);
		if (user != null) {
			String md5p = DigestUtils.md5Hex(p);
			if (md5p.equals(user.getPassword())) {
				ticket = DigestUtils.md5Hex("JT_TICKET_" + System.currentTimeMillis() + u);
				// user 转化成json字符串存入redis
				String userJson = mapper.writeValueAsString(user);
				redisService.set(ticket, userJson);
			}
		}
		return SysResult.oK(ticket);
	}

	public String getUserJsonByTicket(String ticket) {
		String userJson = redisService.get(ticket);
		return userJson;
	}

	

}
